<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="60%">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="110px"
    >
      <el-form-item label="关联客户" prop="customerId">
        <customer-select
          v-model="formData.customerId"
          :disabled="isFromCustomerDetail"
          @change="handleCustomerChange"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="contactId">
        <contact-person-select
          v-model="formData.contactId"
          :customer-id="formData.customerId"
          @change="handleContactChange"
        />
      </el-form-item>
      <el-form-item label="跟进方式" prop="followMethod">
        <el-select v-model="formData.followMethod" placeholder="请选择跟进方式">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.OA_CUSTOMER_FOLLOW_METHOD)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="跟进时间" prop="followTime">
        <el-date-picker
          v-model="formData.followTime"
          type="datetime"
          placeholder="请选择跟进时间"
          value-format="x"
        />
      </el-form-item>
      <el-form-item label="下次沟通时间" prop="nextContactTime">
        <el-date-picker
          v-model="formData.nextContactTime"
          type="datetime"
          placeholder="请选择下次沟通时间"
          value-format="x"
        />
      </el-form-item>
      <el-form-item label="沟通内容" prop="content">
        <el-input
          v-model="formData.content"
          type="textarea"
          placeholder="请输入沟通内容"
          :rows="4"
        />
      </el-form-item>
      
      <el-form-item label="附件路径" prop="files">
        <el-input v-model="formData.files" placeholder="请输入附件路径" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { CustomerFollowUpApi, CustomerFollowUpVO } from '@/api/oa/customerfollowup'
import CustomerSelect from '../customer/components/CustomerSelect.vue'
import ContactPersonSelect from '../customer/components/ContactPersonSelect.vue'

defineOptions({ name: 'CustomerFollowUpForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const formRef = ref() // 表单 Ref
const isFromCustomerDetail = ref(false) // 是否从客户详情页面打开

const formData = ref<CustomerFollowUpVO>({
  id: undefined,
  customerId: undefined,
  customerName: undefined,
  contactId: undefined,
  contactName: undefined,
  followMethod: undefined,
  followTime: undefined,
  content: undefined,
  nextContactTime: undefined,
  files: undefined,
  creatorName: undefined,
  updaterName: undefined
})

const formRules = reactive({
  customerId: [{ required: true, message: '关联客户不能为空', trigger: 'change' }],
  customerName: [{ required: true, message: '客户名称不能为空', trigger: 'blur' }],
  contactId: [{ required: true, message: '联系人不能为空', trigger: 'change' }],
  contactName: [{ required: true, message: '关联联系人ID不能为空', trigger: 'blur' }],
  followMethod: [{ required: true, message: '跟进方式不能为空', trigger: 'change' }],
  followTime: [{ required: true, message: '跟进时间不能为空', trigger: 'change' }],
  content: [{ required: true, message: '沟通内容不能为空', trigger: 'blur' }],
  nextContactTime: [{ required: true, message: '下次沟通时间不能为空', trigger: 'change' }]
})

/** 打开弹窗 */
const open = async (type: string, id?: number, customerInfo?: { customerId: number; customerName: string }) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  // 重置表单
  formRef.value?.resetFields()
  // 重置表单数据
  formData.value = {
    id: undefined,
    customerId: undefined,
    customerName: undefined,
    contactId: undefined,
    contactName: undefined,
    followMethod: undefined,
    followTime: undefined,
    content: undefined,
    nextContactTime: undefined,
    files: undefined,
    creatorName: undefined,
    updaterName: undefined
  }
  // 设置是否从客户详情页面打开
  isFromCustomerDetail.value = !!customerInfo
  if (customerInfo) {
    formData.value.customerId = customerInfo.customerId
    formData.value.customerName = customerInfo.customerName
  }
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await CustomerFollowUpApi.getCustomerFollowUp(id)
      formData.value = data
    } finally {
      formLoading.value = false
    }
  }
}

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (data.id) {
      await CustomerFollowUpApi.updateCustomerFollowUp(data)
      message.success(t('common.updateSuccess'))
    } else {
      await CustomerFollowUpApi.createCustomerFollowUp(data)
      message.success(t('common.createSuccess'))
    }
    dialogVisible.value = false
    // 通知操作成功
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 处理客户选择变化 */
const handleCustomerChange = (customer: any) => {
  if (customer) {
    formData.value.customerName = customer.customerName
    // 清空联系人信息
    formData.value.contactId = undefined
    formData.value.contactName = undefined
  } else {
    formData.value.customerName = undefined
    formData.value.contactId = undefined
    formData.value.contactName = undefined
  }
}

/** 处理联系人选择变化 */
const handleContactChange = (contact: any) => {
  if (contact) {
    formData.value.contactId = contact.id
    formData.value.contactName = contact.contactName
  } else {
    formData.value.contactId = undefined
    formData.value.contactName = undefined
  }
}

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

defineExpose({ open }) // 提供 open 方法，用于打开弹窗
</script>